<?php

namespace app\admin\model;
use think\facade\Db;

class StoreCouponIssue extends BaseModel
{
    /**
     * 数据表主键 
     * @var string
     */
    protected $pk = 'id';


    /**
     * 模型名称
     * @var string
     */
    protected $name = 'store_coupon_issue';  //优惠券发放记录


    protected $insert = ['add_time'];

    public static function stsypage($where)
    {
        $model = self::alias('A')
            ->field('A.*,B.title,B.type')
            ->join('store_coupon B', 'A.cid = B.id')
            ->where('A.is_del', 0)
            ->order('A.id DESC');
        if (isset($where['status']) && $where['status'] != '') {
            $model = $model->where('A.status', $where['status']);
        }
        if (isset($where['type']) && $where['type'] != '') {
            $model = $model->where('B.type', $where['type']);
        }
        if (isset($where['coupon_title']) && $where['coupon_title'] != '') {
            $model = $model->where('B.title', 'LIKE', "%$where[coupon_title]%");
        }
        return self::page($model);
    }

    protected function setAddTimeAttr()
    {
        return time();
    }


    public function coupon(){
        return $this->belongsTo('store_coupon','cid')->bind(['coupon_title'=>'title','type']);
    }

        /**
     * 根据txt文件批量赠送优惠券
     * @param [type] $url txt文件地址
     * @param [type] $couponIssue //优惠券发布记录
     * @return void
     * @author Sam
     * date 2022-01-21
     */
    public function send_coupons_by_txt($url,$couponIssue){
        if(substr(strrchr($url,"."),1) != 'txt'){
            self::setErrorInfo('请上传txt格式文件');
            return false;
        }
        if(!$url || !$couponIssue){
            self::setErrorInfo('参数错误');
            return false;
        } 
        $couponId = self::get($couponIssue);
        if(!$couponId || $couponId->end_time <= time()){
            self::setErrorInfo('优惠券无效');
            return false;
        }
        $peoples  = csv_to_array($url);
        $result   = [];
        array_map(function ($value) use (&$result) {
            $result = array_merge($result, array_values($value));
          }, $peoples);
        if(count($result)){
            $uids = User::where('mobile','in',$result)->column('id');
            foreach ($uids as  $value) {
                StoreCouponUser::addUserCoupon($value, $couponId['cid']);
                StoreCouponIssueUser::addUserIssue($value, $couponId['id']);
            }
        }
        return true;
    }

    /**
     * 类型
     * @param  [type] $value [description]
     * @param  [type] $data  [description]
     * @return [type]        [description]
     */
    public function getTypeNameAttr($value,$data){
        $type = [0=>'通用券',1=>'品类券',2=>'商品券'];
        return $type[$data['type']];
    }

    //领取日期
    public function getReceiveDateAttr($value,$data){
        if($data['start_time']){
            return date('Y/m/d H:i',$data['start_time']).'~'.date('Y/m/d H:i',$data['end_time']);
        }else{
            return  '不限时';
        }
    }

    //发布数量
    public function getPublishNumAttr($value,$data){
        if($data['is_permanent']){
            return  '不限量';
        }else{
            return  '<b style="color: #0a6aa1">发布:'.$data['total_count'].'</b><b style="color:#ff0000;"> / 剩余:'.$data['remain_count'].'</b>';
        }
    }

    //是否消费满赠
    public function getFullNameAttr($value,$data){
        $type = [0=>'否',1=>'是'];
        return $type[$data['is_full_give']];
    }

    //状态
    public function getStatusNameAttr($value,$data){
        $type = [0=>'未开启',1=>'正常',-1=>'已失效'];
        return $type[$data['status']];
    }
    /**
     * 发布优惠券
     * @param $cid
     * @param int $total_count
     * @param int $start_time
     * @param int $end_time
     * @param int $remain_count
     * @param int $status
     * @param int $is_permanent
     * @param int $full_reduction
     * @param int $is_full_give
     * @return StoreCouponIssue|\think\Model
     */
    public static function setIssue($cid, $total_count = 0, $start_time = 0, $end_time = 0, $remain_count = 0, $status = 0, $is_permanent = 0, $full_reduction = 0, $is_full_give = 0)
    {
        return self::create(compact('cid', 'start_time', 'end_time', 'total_count', 'remain_count', 'status', 'is_permanent', 'full_reduction', 'is_full_give'));
    }

    
    public function template(){
        return $this->belongsTo('coupon_template','cid')->bind(['coupon_name'=>'title','type']);
    }
    /**
     * 异步获取当前列表 信息
     * @param $where
     * @return array
     */
    public static function getList($where)
    {
        $data=self::setWhere($where)->page((int)$where['page'],(int)$where['limit'])->select();
        $data=count($data) ? $data->toArray() : [];
        $count=self::setWhere($where)->count();
        return compact('data','count');
    }

    /**
     * 获取查询条件
     * @param $where
     * @param string $alert
     * @param null $model
     * @return SystemUserLevel|null
     */
    public static function setWhere($where,$alert='',$model=null)
    {
        $model=$model===null ? new self() : $model;
        return $model;
    }

 


    /**
     * 查询可用优惠券
     * @param [type] $uid
     * @param [type] $limit
     * @param int $page
     * @param int $type
     * @param int $product_id
     * @return void
     * @author Sam
     * date 2021-09-22
     */
    public static function getCouponList($uid, $limit, $page = 0, $type = 0, $product_id = 0)
    {
        $model1 = self::validWhere('A')->alias('A')
            ->join('store_coupon B', 'A.cid = B.id')
            ->field('A.*,B.type,B.coupon_price,B.use_min_price,B.title')
            ->order('B.sort DESC,A.id DESC');
        $model2 = self::validWhere('A')->alias('A')
            ->join('store_coupon B', 'A.cid = B.id')
            ->field('A.*,B.type,B.coupon_price,B.use_min_price,B.title')
            ->order('B.sort DESC,A.id DESC');
        $model3 = self::validWhere('A')->alias('A')
            ->join('store_coupon B', 'A.cid = B.id')
            ->field('A.*,B.type,B.coupon_price,B.use_min_price,B.title')
            ->order('B.sort DESC,A.id DESC');

        if ($uid) {
            $model1->with(['used' => function ($query) use ($uid) {
                $query->where('uid', $uid);
            }]);

            $model2->with(['used' => function ($query) use ($uid) {
                $query->where('uid', $uid);
            }]);

            $model3->with(['used' => function ($query) use ($uid) {
                $query->where('uid', $uid);
            }]);
        }

         $lst1 = $lst2 = $lst3 = [];
         //全部券
         $lst3 = $model3->where('B.type', 'in',[0,1,2])
         ->where('is_full_give', 0)
         ->select()
         ->hidden(['is_del', 'status'])
         ->toArray();
      
        if ($type == 1 && $product_id > 0) {
                //商品券
                $lst1 = $model1->where('B.type', 2)
                    ->where('is_full_give', 0)
                    // ->where(Db::raw("FIND_IN_SET({$product_id},B.product_id)"))
                    ->whereFindinSet('B.product_id', $product_id)
                    ->select()
                    ->hidden(['is_del', 'status'])
                    ->toArray();
                //品类券
                $cate_id = Goods::where('id', $product_id)->value('cate_id');
                $category = explode(',', $cate_id);
                foreach ($category as $value) {
                    $temp[] = StoreCategory::where('id', $value)->value('pid');
                }
                $temp = array_unique($temp);
                $cate_id = $cate_id . ',' . implode(',', $temp);

                $lst2 = $model2->where('B.type', 1)
                    ->where('is_full_give', 0)
                    ->where('B.category_id', 'in', $cate_id)
                    ->select()
                    ->hidden(['is_del', 'status'])
                    ->toArray();
                $lst3 = [];
        } 
       
        $list = array_merge($lst1, $lst2, $lst3);
        $list = array_unique_fb($list);
        if ($page) $list = array_slice($list, ((int)$page - 1) * $limit, $limit);
        foreach ($list as $k => $v) {
            $v['is_use'] = $uid ? isset($v['used']) : false;
            if (!$v['end_time']) {
                $v['start_time'] = '';
                $v['end_time'] = '不限时';
            } else {
                $v['start_time'] = date('Y/m/d', $v['start_time']);
                $v['end_time'] = $v['end_time'] ? date('Y/m/d', $v['end_time']) : date('Y/m/d', time() + 86400);
            }
            $v['coupon_price'] = $v['coupon_price'];
            $list[$k] = $v;
        }

        if ($list)
            return $list;
        else
            return [];
    }


        /**
     * @param string $prefix
     * @return $this
     */
    public static function validWhere($prefix = '')
    {
        $model = new self;
        if ($prefix) {
            $model->alias($prefix);
            $prefix .= '.';
        }
        $newTime = time();
        return $model->where("{$prefix}status", 1)
            ->where(function ($query) use ($newTime, $prefix) {
                $query->where(function ($query) use ($newTime, $prefix) {
                    $query->where("{$prefix}start_time", '<', $newTime)->where("{$prefix}end_time", '>', $newTime);
                })->whereOr(function ($query) use ($prefix) {
                    $query->where("{$prefix}start_time", 0)->where("{$prefix}end_time", 0);
                });
            })->where("{$prefix}is_del", 0)->where("{$prefix}remain_count > 0 OR {$prefix}is_permanent = 1");
    }


    public function used()
    {
        return $this->hasOne(StoreCouponIssueUser::class, 'issue_coupon_id', 'id')->field('issue_coupon_id');
    }

    /**
     * 优惠券领取
     * @param [int] $id 优惠券id
     * @param [int] $uid 用户id
     * @return void
     * @author Sam
     * date 2021-09-22
     */
    public static function issueUserCoupon($id, $uid)
    {
        $issueCouponInfo = self::validWhere()->where('id', $id)->find();
        if (!$issueCouponInfo) return self::setErrorInfo('领取的优惠劵已领完或已过期!');
        if (StoreCouponIssueUser::where(['uid' => $uid, 'issue_coupon_id' => $id])->count())
            return self::setErrorInfo('已领取过该优惠劵!');
        if ($issueCouponInfo['remain_count'] <= 0 && !$issueCouponInfo['is_permanent']) return self::setErrorInfo('抱歉优惠卷已经领取完了！');
        self::beginTrans();
        $res1 = false != StoreCouponUser::addUserCoupon($uid, $issueCouponInfo['cid']);
        $res2 = false != StoreCouponIssueUser::addUserIssue($uid, $id);
        $res3 = true;
        if ($issueCouponInfo['total_count'] > 0) {
            $issueCouponInfo['remain_count'] -= 1;
            $res3 = false !== $issueCouponInfo->save();
        }
        $res = $res1 && $res2 && $res3;
        self::checkTrans($res);
        return $res;
    }


        /**
     * 订单金额达到预设金额赠送优惠券
     * @param [int] $uid 用户id
     * @param [float] $total_price 订单金额
     * @return void
     * @author Sam
     * date 2021-09-23
     */
    public static function userTakeOrderGiveCoupon($uid, $total_price)
    {
        $couponIds = self::where('status', 1)
            ->where('is_full_give', 1)
            ->where('is_del', 0)
            ->column('id,cid,full_reduction,remain_count,is_permanent');
        if ($couponIds) {
            $couponIssueIds = StoreCouponIssueUser::where('uid', $uid)
                ->whereIn('issue_coupon_id', array_column($couponIds, 'id'))
                ->column('issue_coupon_id');
            foreach ($couponIds as $couponId)
                if ($couponId && !in_array($couponId['id'], $couponIssueIds))
                    if ($total_price >= $couponId['full_reduction'] && ($couponId['is_permanent'] || (!$couponId['is_permanent']) && $couponId['remain_count'] >= 1)) {
                        StoreCouponUser::addUserCoupon($uid, $couponId['cid']);
                        StoreCouponIssueUser::addUserIssue($uid, $couponId['id']);
                        self::where('id', $couponId['id'])->update(['remain_count' => $couponId['remain_count'] - 1]);
                    }
        }
    }

}